package me.zxk.smartagriculture.repository;

import me.zxk.smartagriculture.entity.News;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

/**
 * 新闻数据访问层
 */
@Repository
public interface NewsRepository extends JpaRepository<News, Long> {

    /**
     * 分页查询已发布的新闻
     */
    Page<News> findByStatus(Integer status, Pageable pageable);

    /**
     * 根据关键词搜索已发布的新闻
     */
    @Query("SELECT n FROM News n WHERE n.status = 1 AND " +
           "(n.title LIKE %:keyword% OR n.summary LIKE %:keyword%)")
    Page<News> findByStatusAndKeyword(@Param("keyword") String keyword, Pageable pageable);

    /**
     * 增加新闻浏览数
     */
    @Modifying
    @Query("UPDATE News n SET n.viewCount = n.viewCount + 1 WHERE n.id = :id")
    void incrementViewCount(@Param("id") Long id);

    /**
     * 增加新闻点赞数
     */
    @Modifying
    @Query("UPDATE News n SET n.likeCount = n.likeCount + 1 WHERE n.id = :id")
    void incrementLikeCount(@Param("id") Long id);

    /**
     * 减少新闻点赞数
     */
    @Modifying
    @Query("UPDATE News n SET n.likeCount = n.likeCount - 1 WHERE n.id = :id AND n.likeCount > 0")
    void decrementLikeCount(@Param("id") Long id);

    /**
     * 增加新闻评论数
     */
    @Modifying
    @Query("UPDATE News n SET n.commentCount = n.commentCount + 1 WHERE n.id = :id")
    void incrementCommentCount(@Param("id") Long id);

    /**
     * 减少新闻评论数
     */
    @Modifying
    @Query("UPDATE News n SET n.commentCount = n.commentCount - 1 WHERE n.id = :id AND n.commentCount > 0")
    void decrementCommentCount(@Param("id") Long id);
}
